<template>
    <div class="app-container oneSearchNoFooter">
        <div class="customContainer ">
            <!-- 搜索头 -->
            <el-form :model="formInline" :inline="true" class="demo-form-inline pull-left" size="small">
                <el-form-item>
                    <el-select  v-model="formInline.type" filterable style="width:150px">
                        <el-option v-for="item in type_list" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select  v-model="formInline.is_effective" filterable style="width:100px">
                        <el-option v-for="item in effective_list" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="formInline.name" placeholder="请输入套餐名称" @keyup.enter.native="searchClick">
                    </el-input>
                </el-form-item>
                <dj-button size="small" @search="searchClick" />
            </el-form>
            <el-button class="pull-right" type="primary" size="small" @click="addEditClick()">新增套餐</el-button>

            <!-- 表格 -->
            <el-table highlight-current-row :data="list" v-loading.body="listLoading" border size="mini">
                <el-table-column align="center" label='序号' width="50">
                    <template slot-scope="scope">
                        <span class="indexColor">{{scope.$index+1}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label='套餐名称' prop="name">
                    <template slot-scope="scope">
                        <el-button type="text" @click="addEditClick(scope.row,scope.$index,'look')">{{scope.row.name}}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column align="center" label='适用卡类' prop="type_name"></el-table-column>
                <el-table-column align="center" label='充值金额' prop="money"></el-table-column>
                <el-table-column align="center" label='获得币/星/次数' prop="get_values"></el-table-column>
                <el-table-column align="center" label='优先级' prop="sort"></el-table-column>
                <el-table-column align="center" label='生效时间' width="260" prop="datetime"></el-table-column>
                <el-table-column align="center" label='操作'>
                    <template slot-scope="scope">
                        <el-button @click="addEditClick(scope.row,scope.$index,'edit')" type="primary"
                            icon="el-icon-edit" size="mini"></el-button>
                        <el-button v-if="scope.row.is_enable == 1" type="success" size="mini"
                            @click="stateClick(scope.row.id,scope.$index,0)">已启用</el-button>
                        <el-button v-else size="mini" @click="stateClick(scope.row.id,scope.$index,1)">已停用</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                            @click="delClick(scope.row.id,scope.$index)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 套餐新增编辑弹框 -->
            <el-dialog :close-on-click-modal="false" width="570px" :title="dialogTitle" :visible.sync="addEditDialog"
                @close="callOf('saveForm')" style="margin-top:-5vh">
                <el-form :model="saveForm" :rules="rules" ref="saveForm" class="demo-form-inline" size="small" style="position:relative"  label-position="right" label-width="100px"
                    :key="saveForm.id">
                    <el-form-item label="套餐名称" prop="name">
                        <el-input :disabled="isLook" placeholder="请输入套餐名称20字内" :maxlength="20" v-model="saveForm.name"
                            style="width:300px"></el-input>
                    </el-form-item>
                    <el-form-item label="适用卡类" prop="type">
                        <el-select :disabled="isDisabled"
                            v-model="saveForm.type" style="width:120px"
                            @change="saveFormTypeChange">
                            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="套餐类型" prop="source">
                        <el-select :disabled="isDisabled"
                            v-model="saveForm.source" style="width:120px">
                            <el-option v-for="item in sourceList" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="充值金额" prop="money">
                        <el-input :disabled="isDisabled" type="number" placeholder="请输入金额" :maxlength="6" onmousewheel="return false;" v-model="saveForm.money" style="width:120px"></el-input> 
                    </el-form-item>
                    <el-form-item :label="dialogLabel" prop="get_values">
                        <el-input :disabled="isDisabled" type="number" :placeholder="dialogPlaceholder" :maxlength="6" onmousewheel="return false;" v-model="saveForm.get_values" style="width:120px"></el-input>
                        <span v-show="(saveForm.type==0||saveForm.type==-1)&&saveForm.get_values>saveForm.money" style="margin-left:10px;color:#999">已赠{{giveCoins}}币</span>
                    </el-form-item> 
                    <el-form-item label="获得积分" prop="scores">
                        <el-input :disabled="isDisabled" type="number" placeholder="请输入积分" onmousewheel="return false;" :maxlength="6" v-model="saveForm.scores" style="width:120px"></el-input>
                    </el-form-item> 
                    <el-form-item label="优先级" prop="sort">
                        <el-input :disabled="isLook" type="number" placeholder="请输入优先级" :maxlength="3" onmousewheel="return false;" v-model="saveForm.sort" style="width:120px"></el-input>
                        <span style="margin-left:10px;color:#999">范围1~999,1最大</span>
                    </el-form-item> 
                    <!-- <el-form-item label="赠送" prop="give_values">
                        <el-input :disabled="isDisabled" type="number" :maxlength="6" onmousewheel="return false;"
                            v-model="saveForm.give_values" style="width:120px"></el-input>
                    </el-form-item>  -->
                    <el-form-item label="角标" prop="show_recommend">
                        <el-select :disabled="isLook"
                            v-model="saveForm.show_recommend" style="width:120px">
                            <el-option v-for="item in recommendList" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="生效日期" prop="pickerDate">
                        <el-date-picker style="width:300px" :disabled="isLook" v-model="pickerDate" value-format="yyyy-MM-dd"
                            type="daterange" align="right" unlink-panels range-separator="-" start-placeholder="开始日期"
                            end-placeholder="结束日期" :picker-options="pickerOptions"></el-date-picker>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer" style="margin-top:30px">
                    <el-button v-if="!isLook" type="primary" @click="saveClick('saveForm')" size="small">保存配置
                    </el-button>
                </div>
            </el-dialog>
        </div>
        <!-- 自定义底部 -->
        <div class="bottom_box">
            <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage"
                :page-size="20" layout="prev, pager, next, jumper" :total="totalDataNumber">
            </el-pagination>
        </div>
    </div>
</template>

<script>
    import {
        getList,
        getPage,
        state,
        del,
        save,
    } from "@/api/member/sellCardMeal";
    import { integer0to999999, integer1to999 } from '@/utils/validate';
    import { pickerOptionsAfterF } from '@/utils';
    export default {
        data() {
            const validateVal = (rule, value, callback) => {
                if (!integer0to999999(value)) {
                    callback(new Error('请输入0-999999的整数'))
                } else {
                    callback()
                }
            }
            const validateSort = (rule, value, callback) => {
                if (!integer1to999(value)) {
                    callback(new Error('请输入1-999的整数'))
                } else {
                    callback()
                }
            }
            const validateDate = (rule, value, callback) => {
                if (this.pickerDate.length<2) {
                    callback(new Error('请选择生效日期'))
                } else {
                    callback()
                }
            }
            return {
                type_list: [{ id: '-1', name: '全部' }, { id: '0', name: '会员卡发卡机' }, { id: '1', name: '次卡发卡机' }, { id: '2', name: '星星卡发卡机' }],
                typeList: [{ id: '0', name: '会员卡' }, { id: '1', name: '次卡' }, { id: '2', name: '星星卡' },{id:"-1",name:"临时卡"}],
                recommendList: [{ id: '0', name: '无' }, { id: '1', name: '店长推荐' }],
                effective_list: [{ id: '1', name: '有效套餐' }, { id: '0', name: '失效套餐' }],
                sourceList: [{ id: '1', name: '办卡套餐' }, { id: '0', name: '充值套餐' }],
                list: null,
                isDisabled: true,
                isLook: false,
                listLoading: false,
                addEditDialog: false,
                page: '',
                url: '',
                dialogTitle: '',
                dialogLabel: '获得币数',
                dialogPlaceholder: '请输入币数',
                currentPage:1,
                totalDataNumber:0,
                formInline: {
                    type: "-1",
                    name: "",
                    is_effective: '1',
                },
                pickerDate: [],
                saveForm: {
                    id:null, 
                    type:"0", 
                    source:"1", 
                    money:"", 
                    get_values:"", 
                    scores:"1", 
                    sort:"", 
                    // give_values:"", 
                    show_recommend:"0", 
                    effect_time:"", 
                    stop_time:"", 
                    name:'',
                },
                rules: {
                    name: [
                        { required: true, message: '请输入套餐名称', trigger: 'blur' },
                    ],
                    get_values: [
                        { required: true, validator: validateVal, trigger: 'blur' }
                    ],
                    money: [
                        { required: true, validator: validateVal, trigger: 'blur' }
                    ],
                    scores: [
                        { required: true, validator: validateVal, trigger: 'blur' }
                    ],
                    pickerDate: [
                        { required: true, validator: validateDate, trigger: 'blur' }
                    ],
                    sort: [
                        { required: true, validator: validateSort, trigger: 'blur' }
                    ],
                },
                pickerOptions: pickerOptionsAfterF(),
            };
        },
        beforeRouteEnter(to, from, next) {
            next((vm) => {
                if (!vm.list) {
                    vm.searchClick();
                }
            })
        },
        methods: {
            saveFormTypeChange(){
                this.saveForm.source="1";
                this.sourceList=[{ id: '1', name: '办卡套餐' }]
                if(this.saveForm.type==0||this.saveForm.type==-1){
                    this.dialogLabel="获得币数";
                    this.dialogPlaceholder="请输入币数";
                    this.sourceList=[{ id: '1', name: '办卡套餐' }, { id: '0', name: '充值套餐' }]
                }else if(this.saveForm.type==1){
                    this.dialogLabel="获得次数";
                    this.dialogPlaceholder="请输入次数";
                }else{
                    this.dialogLabel="获得星数";
                    this.dialogPlaceholder="请输入星数";
                } 
            },
            addEditClick(row, index, look) {
                switch (look) {
                    case 'look':
                        this.dialogTitle = '套餐详情';
                        break;
                    case 'edit':
                        this.dialogTitle = '修改套餐';
                        break;
                    default:
                        this.dialogTitle = '新增套餐';
                        break;
                }
                this.isLook = look == 'look' ? true : false;
                this.isDisabled = row ? true : false
                this.saveForm.id = row ? row.id :null;
                this.url = row ? "/Operations_card_machine_config/card_machine_package_edit" :"/Operations_card_machine_config/card_machine_package_create";
                this.saveForm.name = row ? row.name : '';
                this.saveForm.type = row ? row.type : '0';
                this.saveFormTypeChange();
                this.saveForm.source = row ? row.source : '1';
                this.saveForm.money = row ? row.money: '';
                this.saveForm.get_values  = row ? row.get_values : '';
                this.saveForm.scores = row ? row.scores : '';
                this.saveForm.sort = row ? row.sort : '';
                // this.saveForm.give_values = row ? row.give_values : '';
                this.saveForm.show_recommend = row ? row.show_recommend : '0';
                this.pickerDate= row ? [row.datetime.split("--")[0].split(" ")[0],row.datetime.split("--")[1].split(" ")[0]]: [];
                // this.pickerDate[1] = row ? row.datetime.split("--")[1].split(" ")[0] : "";
                // console.log(row,999)
                this.addEditDialog = true;
                
            },
            stateClick(id, index, is_enable) {
                let text = is_enable == '1' ? '是否启用' : '是否停用'
                this.$confirm(text, '提示', { type: 'warning' }).then(() => {
                    state({ id: id, is_enable: is_enable }).then(response => {
                        this.$message({ type: response.code == 1 ? 'success' : 'error', message: response.message });
                        if (response.code == 1) {
                            this.list[index].is_enable = is_enable == 1 ? 1 : 0
                        }
                    });
                })
            },
            saveClick(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.saveForm.effect_time = this.pickerDate[0];
                        this.saveForm.stop_time = this.pickerDate[1];
                        // let data = JSON.parse(JSON.stringify(this.saveForm))
                        save(this.saveForm,this.url).then(response => {
                            this.$message({ type: response.code == 1 ? 'success' : 'error', message: response.message });
                            if (response.code == 1) {
                                this.addEditDialog = false;
                                this.fetchData(this.page);
                            }
                        });
                    }
                });
            },
            delClick(id, index) {
                this.$confirm('确认删除', '提示', { type: 'warning' }).then(() => {
                    del({ id: id }).then(response => {
                        this.$message({
                            type: response.code == 1 ? 'success' : 'error',
                            message: response.message
                        });
                        if (response.code == 1) {
                            this.list.splice(index, 1);
                        }
                    });
                })
            },
            searchClick() {
                this.fatchPage()
            },
            // 表单认证
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            //关闭弹框重置
            callOf(formName) {
                this.addEditDialog = false;
                if (!this.isDisabled) {
                    this.$refs[formName].resetFields();
                }
            },
            fetchData(val="") {
                this.listLoading = true;
                getList(this.formInline,val).then(res => {
                    res.forEach(val=>{
                        // val.type_name=val.device_type==0?"会员卡":val.device_type==1?"次卡":"星星卡";
                        if(val.type_id==1){
                            val.type="1";
                            val.type_name="次卡";
                        }else if(val.type_id==4){
                            val.type="2";
                            val.type_name="星星卡";
                        }else if(val.type_id==0){
                            if(val.card_type_id==0){
                                val.type="0";
                                val.type_name="会员卡";
                            }else{
                                val.type="-1";
                                val.type_name="临时卡";
                            }
                        }
                        val.money/=100;
                    })
                    this.list = res;
                    this.listLoading = false;
                }).catch(res=>{
                    this.listLoading=false;
                })
            },
            // 获取分页
            fatchPage() {
                this.listLoading = true;
                getPage(this.formInline).then(response => {
                    this.totalDataNumber = response * 20;
                    this.fetchData();
                })
            },
            // 分页
            handleCurrentChange(val) {
                this.page=val;
                this.fetchData(val);
            },
        },
        watch:{
            "saveForm.product_id":function(val){
                this.saveForm.product_id=this.saveForm.product_id==null?"":this.saveForm.product_id.replace(/^\s+|\s+$/g, "")
            }
        },
        computed:{
            giveCoins:function(){
                return this.saveForm.get_values-this.saveForm.money;
            }
        }
    };
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    .grop-c {
        .el-input {
            width: 140px;
            margin: 0 10px
        }

        .el-form-item {
            display: inline-block
        }
    }
</style>